package com.baiye.template.config;

import com.alibaba.fastjson.JSON;
import com.baiye.template.common.R;
import org.springframework.security.authentication.*;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/10/27 19:20
 * 登录失败处理逻辑
 */

@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        String msg;
        if (e instanceof AccountExpiredException) {
            msg="账号过期";
        } else if (e instanceof BadCredentialsException) {
            msg="密码错误";
        } else if (e instanceof CredentialsExpiredException) {
            msg="密码过期";
        } else if (e instanceof DisabledException) {
            msg="账号不可用";
        } else if (e instanceof LockedException) {
            msg="账号锁定";
        } else if (e instanceof InternalAuthenticationServiceException) {
            msg="用户不存在";
        }else{
            msg="其他错误";
        }
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(new R().error(msg)));
    }
}

